package com.smart.milvus.bean;

import com.smart.milvus.annotation.DynamicCollection;
import com.smart.milvus.base.DynamicCollectionHandler;
import com.smart.milvus.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class DefaultDynamicHandler implements DynamicCollectionHandler {
    private final DefaultSpElExecutor spElExecutor;
    private final DynamicCollection dynamicCollection;

    public DefaultDynamicHandler(DefaultSpElExecutor spElExecutor, DynamicCollection dynamicCollection) {
        this.spElExecutor = spElExecutor;
        this.dynamicCollection = dynamicCollection;
    }

    @Override
    public String dynamicDatabaseName(Class<? extends MilvusModel<?>> model) {
        return spElExecutor.exec(dynamicCollection.databaseName(), String.class);
    }

    @Override
    public String dynamicCollectionName(Class<? extends MilvusModel<?>> model, String prefix, String format, boolean underCamel) {
        String s = spElExecutor.exec(dynamicCollection.collectionName(), String.class);
        if (StringUtils.isEmpty(s)) {
            return null;
        }
        if (StringUtils.isNotBlank(prefix)) {
            s = prefix + s;
        }
        if (StringUtils.isNotBlank(format)) {
            s = String.format(format, s);
        }
        return s;
    }

    @Override
    public int[] vectorDimension(Class<? extends MilvusModel<?>> model, Field[] fields) {
        DynamicCollection.VectorColumn[] value = dynamicCollection.value();
        Map<String, String> collect = Arrays.stream(value).collect(Collectors.toMap(DynamicCollection.VectorColumn::field, DynamicCollection.VectorColumn::dimension));
        int[] ints = new int[fields.length];
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String dimension = collect.get(field.getName());
            if (StringUtils.isNotBlank(dimension)) {
                ints[i] = spElExecutor.exec(dimension, Integer.class);
            } else {
                ints[i] = 1024;
            }
        }
        return ints;
    }

    @Override
    public int vectorDimension(Class<? extends MilvusModel<?>> model, Field field) {
        DynamicCollection.VectorColumn[] value = dynamicCollection.value();
        Map<String, String> collect = Arrays.stream(value).collect(Collectors.toMap(DynamicCollection.VectorColumn::field, DynamicCollection.VectorColumn::dimension));
        String dimension = collect.get(field.getName());
        if (StringUtils.isNotBlank(dimension)) {
            return spElExecutor.exec(dimension, Integer.class);
        }
        return 1024;
    }
}
